<template>
  <div class="register-form-container">
    <el-form 
      ref="registerFormRef"
      :model="registerForm" 
      :rules="registerRules" 
      label-position="top">
      
      <el-form-item label="用户名" prop="username">
        <el-input 
          v-model="registerForm.username" 
          placeholder="请输入用户名"
          prefix-icon="User" 
          size="large" />
      </el-form-item>
      
      <el-form-item label="密码" prop="password">
        <el-input 
          v-model="registerForm.password" 
          type="password" 
          placeholder="请输入密码"
          prefix-icon="Lock" 
          size="large"
          show-password />
      </el-form-item>
      
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input 
          v-model="registerForm.confirmPassword" 
          type="password" 
          placeholder="请再次输入密码"
          prefix-icon="Lock" 
          size="large"
          show-password />
      </el-form-item>
      
      <el-form-item label="真实姓名" prop="realName">
        <el-input 
          v-model="registerForm.realName" 
          placeholder="请输入真实姓名" />
      </el-form-item>
      
      <el-form-item label="性别" prop="gender">
        <el-select v-model="registerForm.gender" placeholder="请选择性别" style="width: 100%">
          <el-option label="男" value="male"></el-option>
          <el-option label="女" value="female"></el-option>
          <el-option label="保密" value="secret"></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="邮箱" prop="email">
        <el-input 
          v-model="registerForm.email" 
          placeholder="请输入邮箱地址" />
      </el-form-item>
      
      <el-form-item label="手机号" prop="phone">
        <el-input 
          v-model="registerForm.phone" 
          placeholder="请输入手机号码" />
      </el-form-item>
      
      <el-form-item label="兴趣爱好" prop="interests">
        <el-input 
          v-model="registerForm.interests" 
          placeholder="请输入兴趣爱好，多个用、分隔" />
        <div class="form-tip">不填写将随机选择一个兴趣爱好</div>
      </el-form-item>
      
      <el-form-item>
        <el-button 
          type="primary" 
          :loading="loading" 
          class="register-button" 
          size="large"
          @click="handleRegister">
          注册
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { frontRegister } from '@/api/frontAuth'
import { useRouter } from 'vue-router'

// 表单引用和加载状态
const registerFormRef = ref(null)
const loading = ref(false)
const router = useRouter()

// 注册表单数据
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  realName: '',
  gender: 'secret',
  email: '',
  phone: '',
  interests: '',
  birthday: '',
  bio: '',
  avatar: '',
  address: '',
  profession: ''
})

// 表单验证规则
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3到20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  realName: [{ max: 20, message: '真实姓名不超过20个字符', trigger: 'blur' }],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  interests: [{ max: 100, message: '兴趣爱好不超过100个字符', trigger: 'blur' }]
}

// 注册方法
const handleRegister = () => {
  registerFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 处理兴趣爱好默认值
        if (!registerForm.interests || registerForm.interests.trim() === '') {
          const defaultInterests = ['音乐', '讲座', '运动'];
          // 随机选择一个兴趣爱好
          const randomIndex = Math.floor(Math.random() * defaultInterests.length);
          registerForm.interests = defaultInterests[randomIndex];
          console.log('使用随机兴趣爱好:', registerForm.interests);
        }
        
        // 移除确认密码字段，因为后端不需要
        const registerData = { ...registerForm };
        delete registerData.confirmPassword;
        
        const res = await frontRegister(registerData)
        
        if (res.code === 200) {
          ElMessage.success('注册成功，请登录')
          // 注册成功后跳转到登录页
          router.push('/front/login')
        } else {
          ElMessage.error(res.msg || '注册失败，请稍后再试')
        }
      } catch (error) {
        console.error('注册失败:', error)
        
        if (error.response) {
          const errorMsg = error.response.data && error.response.data.msg 
            ? error.response.data.msg 
            : `服务器错误 (${error.response.status})`
          
          ElMessage.error(`注册失败: ${errorMsg}`)
        } else {
          ElMessage.error('注册失败，请稍后再试')
        }
      } finally {
        loading.value = false
      }
    } else {
      ElMessage.warning('请正确填写注册信息')
      return false
    }
  })
}

// 暴露组件方法和属性
defineExpose({
  reset: () => {
    registerFormRef.value.resetFields()
  }
})
</script>

<style scoped>
.register-form-container {
  width: 100%;
}

.register-button {
  width: 100%;
  height: 45px;
  font-size: 16px;
  font-weight: 500;
  letter-spacing: 1px;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}
</style> 